﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.APP.Application.Command.Health;
using Traceability.APP.DTOS;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrerture.Interfaces;

namespace Traceability.APP.Application.CommandHandle.Health
{
    /// <summary>
    /// 保健信息的新增
    /// </summary>
    public class AddHealthCommandHandle:IRequestHandler<AddHealthCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Health_Model> HealthDal;
        private readonly IMapper mapper;
        public AddHealthCommandHandle(IBaseRepository<Health_Model> healthDal, IMapper mapper)
        {
            HealthDal = healthDal;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(AddHealthCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var model = mapper.Map<Health_Model>(request);
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = HealthDal.Add(model).Result;
                tran.Complete();
            }

            if (r > 0)
            {
                result.Code = StateCode.Ok;
                result.Message = "保健信息新增成功";
                return Task.FromResult(result);
            }
            else
            {
                result.Code = StateCode.Faile;
                result.Message = "保健信息新增失败";
                return Task.FromResult(result);
            }

        }




    }
}
